<template>
  <el-form :model="form" label-width="auto" @keydown.enter.prevent="getData">
    <el-row :gutter="12">
      <el-col :span="8">
        <el-form-item label="题目名称">
          <el-input v-model="form.questionName" placeholder="请输入题目名称" @blur="nameBlur" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="题目类型">
          <el-select v-model="form.questionType" clearable placeholder="请选择" style="width: 100%" @change="nameBlur">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>

  <div>
    <el-button type="primary" :disabled="!props.editInfo.id" style="margin-right: 10px"
      @click="handleAddQuestion">新增题目</el-button>
    <el-button type="danger" :disabled="selectIds.length === 0" @click="batchDelete">批量取消</el-button>
    <el-button type="primary" :disabled="selectIds.length === 0" @click="copyToGroup(1)">复制题目至分组</el-button>
    <el-button type="primary" :disabled="selectIds.length === 0" @click="copyToGroup(2)">移动题目至分组</el-button>
    <el-button v-ripple type="primary" @click="handleSyncQuestion" :loading="syncLoading">
      <el-icon>
        <Refresh />
      </el-icon>
      同步官方分组
    </el-button>
  </div>

  <art-table :data="tableData" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal" :loading="tableLoading"
    selection @selection-change="handleSelectionChange" row-key="id" @current-change="currentChange"
    @size-change="sizeChange" style="width: 100%">
    <el-table-column prop="id" label="ID" width="100" #default="scope">
      {{ scope.row.questionId != 0 ? scope.row.questionId : scope.row.id }}
    </el-table-column>
    <el-table-column prop="sort" label="排序" width="160" #default="scope">
      <span v-if="editRowSort !== scope.$index">{{ scope.row.sort }}</span>
      <el-input v-else v-model="scope.row.sort" maxlength="6" show-word-limit style="width: 110px"
        @keydown.enter="submitSort(scope.row.id, scope.row)" />
      <i v-if="editRowSort !== scope.$index" class="iconfont-sys edit-icon"
        @click="editRowSort = editRowSort === scope.$index ? -1 : scope.$index">&#xe65f;</i>
      <i v-else class="iconfont-sys edit-icon" @click="submitSort(scope.row.id, scope.row)">&#xe616;</i>
    </el-table-column>
    <el-table-column label="题目标题" width="700">
      <template #default="scope">
        <div class="cell_padding">
          <div class="bankcont_title">
            <div class="bankcont_title_text">{{ scope.row.questionName }}</div>
            <img src="https://image.lutongjiakao.com/system/e40351a830694bf4b72816bd7b601807.png" alt=""
              class="img_icon" v-if="scope.row.questionAnalysis">
            <img src="https://image.lutongjiakao.com/system/64988bcaaa9241d69d1898c481b09331.png" alt=""
              class="img_icon" v-if="scope.row.fastStudy">
            <img src="https://image.lutongjiakao.com/system/439a87a56fc24d909602740fa95e710e.png" alt=""
              class="img_icon" v-if="scope.row.videoUrl">
            <!-- 题目类型 -->
            <div style="clear: both"></div>
            <!-- end题目类型 -->
          </div>
          <!-- 车型 -->
          <div class="cartcont">
            <div class="cartcont_bigbtn">
              <el-button class="cartcont_btn" v-for="carModelList in scope.row.carModelList" :key="carModelList" round
                size="small">
                {{ carModelList.carName }} ({{ carModelList.carTypes }})
              </el-button>
            </div>
            <div v-for="groupList_one in scope.row.questionGroupList" :key="groupList_one"
              style="display: flex; margin-right: 12px">
              <el-button class="cartcont_btn" v-for="groupList in groupList_one.children" :key="groupList" round
                size="small">
                {{ groupList_one.name }} / {{ groupList.name }}
              </el-button>
            </div>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="图片">
      <template #default="scope">
        <el-image v-if="scope.row.questionImg" style="width: 48px; height: 48px" preview-teleported
          :preview-src-list="[scope.row.questionImg]" hide-on-click-modal :src="scope.row.questionImg"></el-image>
      </template>
    </el-table-column>
    <el-table-column label="题目类型">
      <template #default="scope">
        <el-button v-if="scope.row.questionType == '1'" round size="small" plain>单选题 </el-button>
        <el-button v-if="scope.row.questionType == '0'" round size="small" type="warning" plain>多选题
        </el-button>
        <el-button v-if="scope.row.questionType == '2'" round size="small" type="danger" plain>判断题
        </el-button>
      </template>
    </el-table-column>

    <el-table-column label="来源" prop="questionId">
      <template #default="scope">
        <span v-if="scope.row.questionId != 0">官方题库</span>
        <span v-else>自建题库</span>
      </template>
    </el-table-column>

    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope">
        <button-table type="edit" @click="handleEdit(scope.row)" />
        <button-table type="delete" @click="handleDel([scope.row.id])" />
      </template>
    </el-table-column>
  </art-table>

  <question-type-dialog v-if="showQuestionType" :show-question-type-visible="showQuestionType" :edit-info="editInfo"
    @close-dialog="closeSelectionDialog" />

  <edit-question-dialog v-if="showEditQuestionDialog" :show-edit-question-dialog="showEditQuestionDialog"
    :edit-info="editData" :group-id="props.editInfo.id" @close-dialog="handleCloseEditQuestion">
  </edit-question-dialog>
  <el-dialog v-model="copyDialog" :title="copyType === 1 ? '复制题目' : '移动题目'" width="20%">
    <el-form :model="copyForm" label-width="auto">
      <el-form-item label="选择分组">
        <el-select v-model="copyForm.targetGroupId" clearable placeholder="请选择分组">
          <el-option v-for="item in targetGroupIdList" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="copyDialog = false">取消</el-button>
        <el-button type="primary" :loading="copySubmitLoading" @click="confirmCopy">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { getCanSelectQuestion, delRelationQuestion, syncGroup, getGroupOptions, copyOrMoveGroup, putquestioncategory } from '@/api/questionbank'
import questionTypeDialog from './questionTypeDialog.vue'
import EditQuestionDialog from './EditQuestionDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  showQuestionDetailVisible: {
    type: Boolean
  },
  editInfo: {
    type: Object,
    default: () => {
      return { id: '' }
    }
  },
  syncData: {
    type: Object
  },
  categoryId: {
    type: Number
  }
})

console.log(props.editInfo.id, "props.editInfo.id===");
const editRowSort = ref(-1)

const emit = defineEmits(['uploadGroup'])

const copyDialog = ref(false)

const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const tableLoading = ref(false)
const selectIds = ref<string[]>([])
const showQuestionType = ref(false)
const syncLoading = ref(false)
const editData = ref()
const showEditQuestionDialog = ref(false)

const typeOptions = [
  {
    value: '2',
    label: '判断题'
  },
  {
    value: '1',
    label: '单选题'
  },
  {
    value: '0',
    label: '多选题'
  }
]

const form = reactive({
  questionType: '',
  questionName: ''
})
const copyForm = reactive({
  targetGroupId: ''
})

const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}
const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

function handleSelectionChange(data: any[]) {
  selectIds.value = data.map((item) => item.id)
}

function batchDelete() {
  ElMessageBox.confirm('确定批量取消选择吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleDelete(selectIds.value)
  })
}

function handleDel(ids: string[]) {
  ElMessageBox.confirm('确定取消选择吗？', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleDelete(ids)
  })
}

async function handleDelete(ids: string[]) {
  try {
    const res = await delRelationQuestion({
      questionIds: ids,
      groupIds: props.editInfo.id
    })
    if (res.code === '00000') {
      await getData()
      emit('uploadGroup')
      selectIds.value = []
      ElMessage.success('删除成功')
    }
  } catch (e) {
  } finally {
  }
}

function handleAddQuestion() {
  showQuestionType.value = true
}

function handleCloseEditQuestion(value: any) {
  if (value) {
    getData()
  }
  showEditQuestionDialog.value = false
}

function closeSelectionDialog(value: boolean) {
  showQuestionType.value = false
  if (value) {
    emit('uploadGroup')
    getData()
  }
}

async function getData() {
  const obj: Record<string, any> = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    groupId: props.editInfo.id,
    isGroup: '01',
    carIds: props.editInfo.carIds,
    categoryId: props.editInfo.categoryIds
  }

  for (const key in form) {
    const typedKey = key as keyof typeof form
    if (form[typedKey] !== '') {
      obj[typedKey] = form[typedKey]
    }
  }

  try {
    tableLoading.value = true
    const res = await getCanSelectQuestion(obj)
    if (res.code === '00000') {
      tableData.value = res.data.list
      pageTotal.value = res.data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}

const nameBlur = (e: any) => {
  pageNum.value = 1
  pageSize.value = 10
  getData()
}

function handleEdit(row: any) {
  showEditQuestionDialog.value = true
  editData.value = JSON.parse(JSON.stringify(row))
}

const handleSyncQuestion = async () => {
  const res = await syncGroup({
    categoryIds: props.categoryId,
    name: '1',
    pageUrlType: props.syncData?.pageUrlType
  })
  if (res.code === '00000') {
    ElMessage.success('同步成功')
    emit('uploadGroup')
    getData()
  }
}

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}


const copyType = ref()
const targetGroupIdList = ref<any>([])
const copySubmitLoading = ref(false)
const copyToGroup = async (i: any) => {
  copyType.value = i
  copyDialog.value = true
  const res = await getGroupOptions({
    name: props.editInfo.name,
    id: props.editInfo.id
  })
  if (res.code === '00000') {
    targetGroupIdList.value = res.data.map((e: any) => {
      return {
        label: e.name,
        value: e.id
      }
    })
  }
}
const confirmCopy = async () => {
  try {
    copySubmitLoading.value = true
    const res = await copyOrMoveGroup(filterEmptyValues({
      questionIds: selectIds.value,
      targetGroupId: copyForm.targetGroupId,
      currentGroupId: copyType.value === 1 ? '' : props.editInfo.id,
      type: copyType.value === 1 ? '01' : '02'
    }))
    if (res.code === '00000') {
      ElMessage.success(res.data)
      copyDialog.value = false
      copyForm.targetGroupId = ''
      emit('uploadGroup')
    }
  }
  catch { }
  finally { copySubmitLoading.value = false }
}

const submitSort = async (id: string, ele: any) => {
  const res = await putquestioncategory.putquestioncategoryId(id, {
    questionName: ele.questionName,
    sort: Number(ele.sort),
    questionImg: ele.questionImg,
    questionType: ele.questionType,
    questionA: ele.questionA,
    questionB: ele.questionB,
    questionC: ele.questionC,
    questionD: ele.questionD,
    answer: ele.answer,
    questionAnalysis: ele.questionAnalysis,
    fastStudy: ele.fastStudy,
    videoUrl: ele.videoUrl,
    carIds: ele.carIds,
    categoryId: ele.categoryId,
    groupId: String(props.editInfo.id || '')
  })
  if (res.code === '00000') {
    ElMessage.success('修改成功')
    getData()
    editRowSort.value = -1
  }
}

onMounted(() => {
  if (props.editInfo.id) {
    getData()
  }
})
</script>

<style scoped lang="scss">
.img_icon {
  width: 20px;
  height: 20px;
  margin-left: 10px;
}

.bankcont_title {
  display: flex;
  // align-items: center;
}

.bankcont_title_text {
  float: left;
  // margin-right: 1rem;
  font-weight: bold;
}

.cell_padding {
  padding: 12px 0;
}

.edit-icon {
  margin-left: 4px;
  cursor: pointer;
  color: var(--el-color-primary);
}
</style>
